import React, { Component, PropTypes } from "react"
import { Select, Spin, Icon, Popover } from 'antd'
import 'styles/pay/edit-cell.scss'
import httpFetch from "share/httpFetch"
import { messages } from "share/common"

const { Option } = Select;

class EditSelect extends Component {

  state = {
    editing: false,
    value: this.props.value || {},
    fetching: false,
    option: this.props.option || []
  };

  componentWillReceiveProps = nextProps => {
    if (nextProps.onChangeError) {
      this.setState({ value: nextProps.value })
    }
    if (nextProps.value.key !== this.props.value.key) {
      this.setState({ value: nextProps.value })
    }
  };

  getOption = () => {
    const { url, valueKey, label, value } = this.props;
    if (url) {
      this.setState({ fetching: true, option: [value] });
      httpFetch.get(url).then(res => {
        this.setState({
          fetching: false,
          option: res.data.map(item => Object.assign(item, {key: item[valueKey], label: item[label]}))
        });
      });
    }
  };

  toggleEdit = () => {
    const { disabled } = this.props;
    if (!disabled) {
      this.setState({ editing: true }, () => {
        setTimeout(() => {
          // defaultOpen不会是selection对象在select的div上，导致keyDown事件失效
          this.inputRef.rcSelect.selectionRef.click();
        }, 0)
      });
      this.getOption();
    }
  };

  changeBlur = () => {
    const { blurChange } = this.props;
    this.setState({ editing: false }, () => {
      blurChange && this.changeValue(this.state.value.key)
    });
  };

  changeValue = res => {
    const { option, value } = this.state;
    let result = option.find(item => item.key === res);
    this.setState({ value: res === value.key ? value : result, editing: false }, () => {
      this.onChange(result);
    });
  };

  onChange = result => {
    const { onChange } = this.props;
    onChange(result.key, result);
  };

  render() {
    const { editing, value, option, fetching } = this.state;
    const { popOver } = this.props;
    let children = editing ? (
      <Select
        onBlur={this.changeBlur}
        value={value.key}
        onFocus={this.getOption}
        notFoundContent={fetching ? <Spin size="small" /> : messages('common.unmatched')/*无匹配结果*/}
        onChange={this.changeValue}
        style={{ width: '100%' }}
        ref={inputRef => this.inputRef = inputRef}
      >
        {option.map(item => <Option key={item.key}>{item.label}</Option>)}
      </Select>
    ) : (
      <div className='simulate-form' onClick={this.toggleEdit}>
        <span className='edit-cell-show'>{popOver ? <Popover content={popOver()}>{value.label}</Popover> : value.label}</span>
        <Icon type="edit" className="editable-cell-icon" />
      </div>
    );
    return (
      <div>{children}</div>
    )
  }

  static propTypes = {
    value: PropTypes.object
  };

  static defaultProps = {
    value: {}
  }

}

export default EditSelect
